package client.comm.baoding.ui

import android.Manifest
import android.app.AlertDialog
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.graphics.Color
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.KeyEvent
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.navigation.NavController
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.NavigationUI
import androidx.navigation.ui.setupWithNavController
import client.comm.baoding.BaseMiddleActivity
import client.comm.baoding.R
import client.comm.baoding.databinding.ActivityMainBinding
import client.comm.baoding.receiver.MeBroadcast
import client.comm.baoding.ui.vm.MainViewModel
import client.comm.commlib.toast.toast
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import java.util.*
import client.comm.commlib.utils.SharedUtil
import com.amap.api.maps.MapsInitializer

class MainActivity : BaseMiddleActivity<MainViewModel, ActivityMainBinding>() {

    override fun getLayout(): Int {
        return R.layout.activity_main
    }

    //    val meBroadcast: MeBroadcast by lazy {
//        MeBroadcast()
//    }
    var mLocationClient: AMapLocationClient? = null
    private fun destroyLocation() {
        if (null != mLocationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            mLocationClient?.onDestroy()
            mLocationClient = null
            mLocationClient = null
        }
    }

    fun privacyCompliance() {
        if (!SharedUtil.read("privacyShow", false)) {
            MapsInitializer.updatePrivacyShow(this@MainActivity, true, true)
            val spannable =
                SpannableStringBuilder("\"请同意获取定位权限；\n")
//            spannable.setSpan(
//                ForegroundColorSpan(Color.BLUE),
//                35,
//                42,
//                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
//            )
            AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage(spannable)
                .setPositiveButton(
                    "同意"
                ) { dialogInterface, i ->
                    MapsInitializer.updatePrivacyAgree(this@MainActivity, true)
                    SharedUtil.save("privacyShow", true)

                    requestExternalStorage()
                }
                .setNegativeButton(
                    "不同意"
                ) { dialogInterface, i ->
                    MapsInitializer.updatePrivacyAgree(
                        this@MainActivity,
                        false
                    )
                    SharedUtil.save("privacyShow", false)
                }
                .show()
        } else {
            requestExternalStorage()

        }


    }

    fun requestExternalStorage() {
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        ) {//有權限
            getLocat()
        } else {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                0x99
            )
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED && requestCode == 0x99
        ) {//有權限
            getLocat()
        }
    }


    fun getLocat() {

        //声明AMapLocationClient类对象
        //声明定位回调监听器
        //初始化定位
        mLocationClient = AMapLocationClient(applicationContext)
        //设置定位回调监听
        //设置定位回调监听
        mLocationClient?.setLocationListener(object : AMapLocationListener {
            override fun onLocationChanged(p0: AMapLocation?) {
                p0?.city?.let {
                    viewModel.location.value = it
                }
            }
        })

        //声明AMapLocationClientOption对象
        //声明AMapLocationClientOption对象
        var mLocationOption: AMapLocationClientOption? = null
        //初始化AMapLocationClientOption对象
        //初始化AMapLocationClientOption对象
        mLocationOption = AMapLocationClientOption()

        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);

        mLocationClient?.setLocationOption(mLocationOption);


        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);

        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);

        mLocationOption.setOnceLocation(true);

        //获取最近3s内精度最高的一次定位结果：
        mLocationOption.setOnceLocationLatest(true);

        mLocationOption.setInterval(1000);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);

        //设置是否允许模拟位置,默认为true，允许模拟位置
        mLocationOption.setMockEnable(true);

        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(20000);

        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);


        //给定位客户端对象设置定位参数
        mLocationClient?.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient?.startLocation();
    }

    override fun onDestroy() {
        super.onDestroy()
//        unregisterReceiver(meBroadcast)
        destroyLocation()
    }

    override fun initViewModel(): MainViewModel = createViewModel()

    val controller: NavController by lazy {
        findNavController(R.id.nav_host_fragment)
    }

    override fun initView() {
//        registerReceiver(meBroadcast, IntentFilter(MeBroadcast.MAIN_SWITCH_TAB))
        controller?.let {
            binding.navView.setupWithNavController(it)
        }

//        controller?.let { binding.navView.setupWithNavController(it) }
//        val navHostFragment = supportFragmentManager
//            .findFragmentById(R.id.nav_host_fragment) as NavHostFragment?
//        val navController = navHostFragment!!.navController
//        NavigationUI.setupActionBarWithNavController(this, navController)
//        NavigationUI.setupWithNavController(binding.navView, navController)
        binding.vm = viewModel
    }

    override fun observerUI() {
        viewModel.switchValue.observe(this, Observer {
            if (it >= 0) {
                when (it) {
                    1 -> {
                        binding.navView.selectedItemId = R.id.navigation_cate
//                        controller.navigate(R.id.navigation_cate)
                    }
//                    3 -> {
//                        controller.navigate(R.id.navigation_me)
//                    }
//                    2 -> {
//                        controller.navigate(R.id.navigation_buycart)
//                    }
//                    0 -> {
//                        controller.navigate(R.id.navigation_home)
//                    }
                }
            }
        })
    }

    fun switchTab(tab: Int) {
        viewModel.switchValue.value = tab
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitLogin()
        }
        return false
    }

    private var isExit = false

    private fun exitLogin() {
        var tExit: Timer? = null
        if (!isExit) {
            isExit = true
            toast("再次返回退出${getString(R.string.app_name)}")
            tExit = Timer()
            tExit.schedule(object : TimerTask() {
                override fun run() {
                    isExit = false //取消退出
                }
            }, 2500) // 如果2.5秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            System.exit(0)
        }
    }


}